import java.io.*;
import java.net.*;

import org.apache.log4j.Logger;

/**
 * TCPServer, the entry class of the TCPServer program.
 * 
 * @author Xiaohui Li
 * 
 */
class TCPServer {
	/**
	 * Logger goes here
	 */
	private static org.apache.log4j.Logger log = Logger
			.getLogger(TCPServer.class);
	/**
	 * Entry main method
	 * 
	 * @param argv
	 * @throws Exception
	 */
	public static void main(String argv[]) throws Exception {
		String fromclient; // received string
		int portnumber = 5301; // port number
		ServerSocket Server = new ServerSocket(portnumber); // init the server
		
		log.info("TCPServer listening on port:" + portnumber);

		// run server
		while (true) {
			try {
				Socket connected = Server.accept(); // server ready to listen
				// This line will be printed out when a client is connected.
				log.info("THE CLIENT" + " " + connected.getInetAddress() + ":"
						+ connected.getPort() + " IS CONNECTED ");

				BufferedReader inFromClient = new BufferedReader(
						new InputStreamReader(connected.getInputStream()));

				while (true) {
					fromclient = inFromClient.readLine();

					// if client init disconnection
					if (fromclient.equals("q") || fromclient.equals("Q")) {
						connected.close();
						break;
					}

					// otherwise process upload data
					else {
						String gpsdata = fromclient.trim();
						if (gpsdata == null
								|| !Character.isDigit(gpsdata.charAt(0))) {
							log.warn("DATA from CLIENT: " + gpsdata);
						} else {
							// parse uploaded data and insert entry into
							// database
							StrParser parser = new StrParser(gpsdata);
							ConnMaker maker = new ConnMaker();
							maker.insertDB(parser);
							log.info("RECIEVED INTO DB:" + fromclient);
							// remember to close database connection after data
							// is inserted
//							maker.closeConn();
						}
					}

				}
			} catch (Exception e) {
				// e.printStackTrace();
				System.err.println("Exception: Connection closed.");
			}

		}
	}
}
